
package com.yzd.netmonitor.web.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.yzd.netmonitor.util.SignUtils;
import com.yzd.netmonitor.web.RespBody;
import com.yzd.netmonitor.web.RespBodyBuilder;
import com.yzd.netmonitor.web.ResponseCode;

//HandlerInterceptorAdapter一般用于：用户是否登录，权限设置，日志记录
public class SignVerifyInterceptor extends HandlerInterceptorAdapter {

	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SignVerifyInterceptor.class);

	private RespBodyBuilder respWriter = new RespBodyBuilder();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		logger.info("preHandle method run...");
		String channelId = request.getHeader("channel_id");
		if (StringUtils.isBlank(channelId)) {
			print(response, respWriter.toError(ResponseCode.CODE_600));
			return false;
		}
		String enc = request.getParameter("enc");
		if (StringUtils.isBlank(enc)) {
			print(response, respWriter.toError(ResponseCode.CODE_601));
			return false;
		}
		Map<String, String[]> map = request.getParameterMap();
		TreeMap<String, String> params = new TreeMap<>();
		Set<Entry<String, String[]>> items = map.entrySet();
		for (Entry<String, String[]> item : items) {
			String pName = item.getKey();
			String[] pValues = item.getValue();
			if (ArrayUtils.isNotEmpty(pValues)) {
				String pValue = StringUtils.join(pValues, ',');
				logger.info("pName:{},pValue:{}", pName, pValue);
				params.put(pName, pValue);
			}
		}
		String signStr = SignUtils.sign(params, "");
		if (!StringUtils.equalsIgnoreCase(enc, signStr)) {
			print(response, respWriter.toError(ResponseCode.CODE_600));
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	private void print(HttpServletResponse response, RespBody respBody) throws IOException {

		try (PrintWriter out = response.getWriter()) {
			out.println(JSON.toJSONString(respBody));
			out.flush();
		}
	}
}
